import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# 加载数据
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)

# 显示前五行数据
print(df.head())

# 使用 matplotlib 中的条形图可视化企鹅物种的分布
plt.figure(figsize=(8, 6))
df['Species'].value_counts().plot(kind='bar', color=['skyblue', 'lightgreen', 'coral'])
plt.title('Penguin Species Distribution')
plt.xlabel('Species')
plt.ylabel('Count')
plt.show()

# 使用箱线图可视化每个物种的 FlipperLength、CulmenLength 和 CulmenDepth 分布情况
plt.figure(figsize=(14, 8))
plt.subplot(1, 3, 1)
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.title('Flipper Length Distribution')

plt.subplot(1, 3, 2)
sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.title('Culmen Length Distribution')

plt.subplot(1, 3, 3)
sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.title('Culmen Depth Distribution')

plt.tight_layout()
plt.show()

# 显示缺少值的行
print("Missing values:")
print(df[df.isnull().any(axis=1)])

# 删除缺少值的行
df_cleaned = df.dropna()

# 将数据拆分为特征和标签
X = df_cleaned[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
y = df_cleaned['Species']

# 将数据拆分为训练集和测试集，30%为测试数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 创建多类逻辑回归模型
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)

# 训练模型
model.fit(X_train, y_train)

# 1. 预测测试集的标签
y_pred = model.predict(X_test)

# 2. 计算模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Model accuracy: {accuracy:.2f}')

# 额外评估：输出分类报告和混淆矩阵
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))
